<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------


namespace app\index\controller;

use app\index\BaseController;
use app\index\model\charge\ChargingStation;
use app\index\model\sms\SmsRecord;
use app\index\model\user\UserBill;
use app\index\model\user\UserCar;
use app\index\model\user\UserDayData;
use app\index\model\user\UserMonthData;
use app\index\model\user\UserPileRelation;
use app\index\model\user\UserStationCollection;
use Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use app\index\model\user\User as UserModel;
use think\facade\Request;

/**
 * Class Auth
 * @package app\controller\api
 * @author xaboy
 * @day 2020-05-06
 */
class User extends BaseController
{

    /**
     * 充电站收藏操作
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function collectStation(){
        $getData = Request::post();
        if(!$getData['station_id']) return $this->fail('请选择要收藏的充电站点');
        if(!isset($getData['type']) || !$getData['type']) $getData['type'] = 1;
        $userId = $this->request->uid();
        $where = ['user_id'=>$userId,'station_id'=>$getData['station_id']];
        $collectStationModel = new UserStationCollection();
        $checkInfo = $collectStationModel->getInfoByWhere($where);
        //收藏站点
        if($getData['type'] == 1){
            if($checkInfo) return $this->success('收藏成功');
            $addResult = $collectStationModel->addUserCollection($userId,$getData);
            if(!$addResult) return $this->fail('收藏失败，请稍后操作');
            return $this->success('收藏成功');
        //取消收藏
        }else if($getData['type'] == 2){
            if(!$checkInfo) return $this->success('取消收藏成功');
            $deleteResult = $collectStationModel->deleteUserCollection($where);
            if(!$deleteResult) return $this->fail('取消收藏失败，请稍后重试');
            return $this->success('取消收藏成功');
        }else{
            return $this->success('设置成功');
        }
    }

    /**
     * 用户收藏列表
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function collectList(){
        $getData = $this->request->param();
        [$page,$limit] = $this->getPage();
        $userId = $this->request->uid();
        $getData['user_id'] = $userId;
        $chargingStationModel = new ChargingStation();
        if(!isset($getData['page'])) $getData['page'] = 1;
        if(!isset($getData['limit'])) $getData['limit'] = 15;
        $getData['set_order'] = ['u.id'=>'desc'];
        $field = "s.id,s.title,s.icon_img,s.longitude,s.latitude,s.max_power,s.station_remark,s.remark,s.parking_remark,s.is_open,u.station_id";
        $getList = $chargingStationModel->myCollectionStation($getData,$page,$limit,$field);
        foreach ($getList['list'] as $key=>$value){
            $getList['list'][$key]['is_collect'] = 1;
        }
        return $this->success('获取内容成功',$getList);
    }

    /**
     * 忘记登录密码
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function changePassword()
    {
        $data = Request::post();
        if(!isset($data['phone']) || !$data['phone'])  return $this->fail('请填写手机号');
        if(!isset($data['sms_code']) || !$data['sms_code']) return $this->fail('请填写验证码');
        if(!isset($data['change_pwd']) || !$data['change_pwd']) return $this->fail('请填写新密码');
        $userModel = new UserModel();
        $user = $userModel->getUserByAccount($data['phone']);
        if (!$user) return app('json')->fail('用户不存在');
        if($user['status'] == 0) return $this->fail('当前用户被禁用，请联系客服');
        $smsRecordModel = new SmsRecord();
        //验证码判断
        $smsWhere = ['phone'=>$data['phone'],'type'=>'changePwd'];
        $getInfo = $smsRecordModel->where($smsWhere)->order('sms_record_id','desc')->find();
        //判断验证码是否正确
        if(!$getInfo || $getInfo['code'] != $data['sms_code']){
            return $this->fail('验证码错误');
        }
        if((strtotime($getInfo['create_time']) + 30*60) < time() || $getInfo['is_use'] == 1){
            return $this->fail('验证码已经过期');
        }

        $saveData = [
            'log_pwd' => password_hash($data['change_pwd'], PASSWORD_BCRYPT),
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $result = $userModel->updateUserInfo($user['id'],$saveData);
        if($result){
            return $this->success('修改成功');
        }else{
            return $this->fail('修改失败');
        }
    }

    /**
     * 修改登录密码
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function changeUserPwd(){
        $data = Request::post();
        if(!isset($data['old_pwd']) || !$data['old_pwd']) return $this->fail('请填写登录密码');
        if(!isset($data['login_pwd']) || !$data['login_pwd']) return $this->fail('请填写新的登录密码');
        if(!isset($data['confirm_pwd']) || !$data['confirm_pwd']) return $this->fail('请填写确认新的登录密码');
        if($data['login_pwd'] != $data['confirm_pwd']) return $this->fail('两次输入的登录密码不一致');
        $userId = $this->request->uid();
        $userModel = new UserModel();
        $user = $userModel->getUserInfoById($userId);
        if (!$user) return app('json')->fail('用户不存在');
        if($user['status'] == 0) return $this->fail('当前用户被禁用，请联系客服');
        if (!password_verify($pwd = (string)$data['old_pwd'], $user['log_pwd'])){
            return $this->fail('填写的密码错误');
        }
        $saveData = [
            'log_pwd' => password_hash($data['login_pwd'], PASSWORD_BCRYPT),
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $result = $userModel->updateUserInfo($user['id'],$saveData);
        if($result){
            return $this->success('修改成功');
        }else{
            return $this->fail('修改失败');
        }
    }

    /**
     * 用户上传头像
     * @return $this
     */
    function uploadUserImg(){
        $userId = $this->request->uid();
        $file = $this->request->file("userImg");
        $dirDay = date("Y")."/".date("m");
        $fieldName = \think\facade\Filesystem::disk('index')->putFile("/webImg/".'userImg'."/".$dirDay,$file);
        if($fieldName){
            $userModel = new UserModel();
            $saveData = [
                'avatar' => config('add.web_url')."/upload/".$fieldName,
                'update_time'=>date("Y-m-d H:i:s"),
            ];
            $result = $userModel->updateUserInfo($userId,$saveData);
            if($result){
                return $this->success('修改成功',['showImg'=>config('add.web_url')."/upload/".$fieldName,]);
            }else{
                return $this->fail('修改失败');
            }
        }else{
            return $this->fail('修改失败');
        }
    }

    /**
     * 设置支付密码
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function setPayPwd(){
        $data = Request::post();
        if(!$data['sms_code']) return $this->fail('请填写验证码');
        if(!$data['pay_pwd']) return $this->fail('请填写支付密码');
        if(!$data['confirm_pwd']) return $this->fail('请填写确认支付密码');
        if($data['confirm_pwd'] != $data['pay_pwd']) return $this->fail('两次输入的支付密码不一致');
        $userModel = new UserModel();
        $userId = $this->request->uid();
        $user = $userModel->getUserInfoById($userId);
        if (!$user) return app('json')->fail('用户不存在');
        if($user['status'] == 0) return $this->fail('当前用户被禁用，请联系客服');
        $smsRecordModel = new SmsRecord();
        //验证码判断
        $smsWhere = ['phone'=>$user['account'],'type'=>'setPayPwd'];
        $getInfo = $smsRecordModel->where($smsWhere)->order('sms_record_id','desc')->find();
        //判断验证码是否正确
        if(!$getInfo || $getInfo['code'] != $data['sms_code']){
            return $this->fail('验证码错误');
        }
        if((strtotime($getInfo['create_time']) + 30*60) < time() || $getInfo['is_use'] == 1){
            return $this->fail('验证码已经过期');
        }
        $saveData = [
            'pay_pwd' => password_hash($data['pay_pwd'], PASSWORD_BCRYPT),
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $result = $userModel->updateUserInfo($user['id'],$saveData);
        if($result){
            return $this->success('设置成功');
        }else{
            return $this->fail('设置失败');
        }
    }

    /**
     * 绑定汽车列表
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function userCarList(){
        [$page,$limit] = $this->getPage();
        if(!isset($getData['page'])) $getData['page'] = 1;
        if(!isset($getData['limit'])) $getData['limit'] = 15;
        $userId = $this->request->uid();
        $userCarModel = new UserCar();
        $field = 'id,user_id,car_brand,car_model,car_number,is_authentication,create_time,car_image';
        $getList = $userCarModel->getUserCarList($userId,$field,$page,$limit);
        return $this->success('获取内容成功',$getList);
    }

    /**
     * 绑定汽车
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function userCarInfo(){
        $userId = $this->request->uid();
        $id = $this->request->param('id');
        if(!$id) return $this->fail('请选择车辆');
        $where = ['id'=>$id,'user_id'=>$userId];
        $userCarModel = new UserCar();
        $field = '*';
        $getInfo = $userCarModel->getInfoByWhere($where,$field);
        if(!$getInfo) return $this->fail('请选择正确的车辆');
        return $this->success('获取内容成功',$getInfo);
    }

    /**
     * 绑定汽车
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function userBindCar(){
        $data = Request::post();
        $data['user_id'] = $this->request->uid();
        //if(!isset($data['car_brand']) || !$data['car_brand']) return $this->fail('请填写汽车品牌');
        //if(!isset($data['car_model']) || !$data['car_model']) return $this->fail('请填写汽车型号');
        //if(!isset($data['car_type']) || !$data['car_type']) return $this->fail('请选择汽车类型');
        if(!isset($data['car_number']) || !$data['car_number']) return $this->fail('请输入车牌号码');
        $userCarModel = new UserCar();
        $carInfo = $userCarModel->getInfoByWhere(['user_id'=>$data['user_id'],'car_number'=>$data['car_number']]);
        if($carInfo) return $this->fail('当前车辆已经绑定');
        $result = $userCarModel->addUserCard($data);
        if($result){
            return $this->success('绑定成功');
        }else{
            return $this->fail('绑定失败，请稍后重试');
        }
    }

    /**
     * 删除绑定汽车
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function deleteUserCar(){
        $data = Request::post();
        if(!$data['id']) return $this->fail('请选择要解除绑定的汽车');
        $data['user_id'] = $this->request->uid();
        $userCarModel = new UserCar();
        $getInfo = $userCarModel->getInfoById($data['id']);
        if($getInfo['user_id'] != $data['user_id']) return $this->fail('请选择正确的要绑定的汽车');
        $saveData = [
            'update_time'=>date("Y-m-d H:i:s"),
            'is_delete'=>0,
        ];
        $result = $userCarModel->updateUserCar($getInfo['id'],$saveData);
        if($result){
            return $this->success('删除成功');
        }else{
            return $this->fail('删除失败，请稍后重试');
        }

    }

    /**
     * 更新绑定汽车
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function updateBindCar(){
        $getData = Request::post();
        $getData['user_id'] = $this->request->uid();
        //if(!isset($data['car_brand']) || !$data['car_brand']) return $this->fail('请填写汽车品牌');
        //if(!isset($data['car_model']) || !$data['car_model']) return $this->fail('请填写汽车型号');
        //if(!isset($data['car_type']) || !$data['car_type']) return $this->fail('请选择汽车类型');
        if(!isset($getData['car_number']) || !$getData['car_number']) return $this->fail('请输入车牌号码');
        if(!isset($getData['id']) || !$getData['id']) return $this->fail('选择要设置的车辆');
        $userCarModel = new UserCar();
        $carInfo = $userCarModel->getInfoByWhere(['user_id'=>$getData['user_id'],'car_number'=>$getData['car_number']]);
        if($carInfo && $carInfo['id'] != $getData['id']) return $this->fail('当前车辆已经绑定');
        $saveData = [
            'car_brand'=>$getData['car_brand'],
            'car_model'=>$getData['car_model'],
            'car_type'=>isset($getData['car_type']) ? $getData['car_type'] : '',
            'car_number'=>$getData['car_number'],
            'car_image'=>isset($getData['car_image']) ? $getData['car_image'] : '',
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $result = $userCarModel->updateUserCar($getData['id'],$saveData);
        if($result){
            return $this->success('设置成功');
        }else{
            return $this->fail('设置失败，请稍后重试');
        }
    }

    /**
     * 车辆验证
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function bindCarAuthentication(){
        $getData = Request::post();
        $getData['user_id'] = $this->request->uid();
        if(!isset($getData['id']) || !$getData['id']) return $this->fail('选择要设置的车辆');
        if(!isset($getData['vin_number']) || !$getData['vin_number']) return $this->fail('请填写vin码');
        if(!isset($getData['use_type']) || !$getData['use_type']) return $this->fail('请选择车辆类型');
        if(!isset($getData['driving_img']) || !$getData['driving_img']) return $this->fail('请上传行驶证图片');
        if(!isset($getData['car_brand']) || !$getData['car_brand']) return $this->fail('请选择车辆品牌');
        if(!isset($getData['car_model']) || !$getData['car_model']) return $this->fail('请选择车辆型号');
        $userCarModel = new UserCar();
        $carInfo = $userCarModel->getInfoByWhere(['user_id'=>$getData['user_id'],'id'=>$getData['id']]);
        if(!$carInfo) return $this->fail('选择正确的车辆');
        if($carInfo['is_authentication'] == 1) return $this->fail('车辆已经验证');
        $saveData = [
            'vin_number'=>$getData['vin_number'],
            'use_type'=>$getData['use_type'],
            'car_brand'=>$getData['car_brand'],
            'car_model'=>$getData['car_model'],
            'driving_img'=>isset($getData['driving_img']) ? $getData['driving_img'] : '',
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        $saveData['is_authentication'] = 1;
        $result = $userCarModel->updateUserCar($getData['id'],$saveData);
        if($result){
            return $this->success('验证成功');
        }else{
            return $this->fail('验证失败，请稍后重试');
        }
    }

    //修改用户资料
    function saveUserInfo(){
        $getData = Request::post();
        if(!$getData['nickname']) return $this->fail('请输入昵称');
        $saveData = [
            'nickname'=>$getData['nickname'],
            'update_time'=>date("Y-m-d H:i:s"),
        ];
        if(isset($getData['sex']) && $getData['sex']) $saveData['sex'] = $getData['sex'];
        if(isset($getData['real_name'])  && $getData['real_name']) $saveData['real_name'] = $getData['real_name'];

        $userModel = new UserModel();
        $userResult = $userModel->updateUserInfo($this->request->uid(),$saveData);
        if($userResult) return $this->success('修改成功');
        return $this->fail('修改失败');
    }

    /**
     * 我的充电桩
     * @return $this
     */
    function myPile(){
        $userId = $this->request->uid();
//        print_r($userId);die;
        [$page,$limit] = $this->getPage();
        $userPileModel = new UserPileRelation();
        $getList = $userPileModel->getUserPileList($userId,$page,$limit);
        return $this->success('获取成功',$getList);
    }

    /**
     * 用户账单列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function userBill(){
        [$page,$limit] = $this->getPage();
        $uid = $this->request->uid();
        $where = ['uid'=>$uid];
        $userBillModel = new UserBill();
        return $this->success('获取成功',$userBillModel->userBillList($where,$page,$limit));
    }
    function community(){
        $result = Db::table('jy_community')->select();
        return $this->success('获取成功',$result);
    }
    function Applytj(){
        $getData = Request::post();
        $uid = $this->request->uid();
        $getData['uid'] = $uid;
        $getData['createTime'] = time();
        $insertId = Db::table('jy_community2')->insert($getData);
        return $this->success('成功申请');
    }
    public function tixian(){
        $getData = Request::post();
//        if($getData['money'] < 100) return $this->fail('提现金额不能小于100');
        $getData['uid'] = $this->request->uid();
//        $money = Db::table('jy_user')->where(['id' => $getData['uid']])->value('now_money') - Db::table('jy_user_bank')->where(['uid' => $getData['uid']])->sum('money');

        $list = Db::table('jy_danzhuang')->where('uid',$getData['uid'])->select()->toArray();
        $total_price = 0;
        foreach ($list as &$item){
            $total_price += Db::table('jy_charge_ykc_order')->where('charge_terminal',$item['dzname'])->sum('total_price');
        }
        $ytx = Db::table('jy_user_bank')->where(['uid'=>$getData['uid']])->sum('money');

        if($getData['money'] > $total_price+$ytx) return $this->fail('可提现余额不足');
        $getData['status'] = 0;
        $getData['create_time'] = time();

        Db::table('jy_user_bank')->insert($getData);
        return $this->success('提现成功,等待审核');
    }
    public function tixianlist(){
        $getData = Request::post();
        $uid = $this->request->uid();
        if(isset($getData['status'])&&$getData['status'] !== 3){
            return $this->success('提现列表', Db::table('jy_user_bank')->where(['status'=>$getData['status']])->where(['uid'=>$uid])->select());

        }else{
            return $this->success('提现列表', Db::table('jy_user_bank')->where(['uid'=>$uid])->select());
        }
    }

    public function nummoney(){

        $money = Db::table('jy_user_bank')->where(['uid' => $this->request->uid()])->sum('money');
        $data=[
            'money'=>$money
        ];
        return $this->success('成功',$data );
    }


}
